package cn.org.book.shop.app.controller;

import cn.org.book.shop.article.domain.ApArticleDataConfiguration;
import cn.org.book.shop.common.constant.HttpStatus;
import cn.org.book.shop.common.core.controller.BaseController;
import cn.org.book.shop.common.core.page.PageDomain;
import cn.org.book.shop.common.core.page.TableDataInfo;
import cn.org.book.shop.common.core.page.TableSupport;
import cn.org.book.shop.common.utils.StringUtils;
import cn.org.book.shop.common.utils.sql.SqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * app服务baseController
 */
public class AppBaseController extends BaseController {
    /**
     * 设置请求分页数据
     * 关闭分页优化
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, true, false, true)
                    .setOrderBy(orderBy);
        }
    }

    protected TableDataInfo getDataTable(List<?> data, List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(data);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    protected List changeApArticleDataConfiguration(List<ApArticleDataConfiguration> apArticleDataConfigurations) {
        List<Map> maps = new ArrayList<>();
        if (apArticleDataConfigurations == null || apArticleDataConfigurations.isEmpty()) {
            return maps;
        }
        final Map<String, List<ApArticleDataConfiguration>> map = new HashMap<>();
        apArticleDataConfigurations.forEach(item -> {
            List<ApArticleDataConfiguration> apArticleDataConfigurationList = map.get(item.getDisplayType());
            if (apArticleDataConfigurationList == null || apArticleDataConfigurationList.isEmpty()) {
                ArrayList<ApArticleDataConfiguration> newList = new ArrayList<>();
                newList.add(item);
                map.put(item.getDisplayType(), newList);
            } else {
                apArticleDataConfigurationList.add(item);
            }
        });
        maps.add(map);
        return maps;
    }
}
